<html>
<head> 管理api</head>
<body>

<p> ---------------token---------------</p>

<div>
    <input type="text" id="input_uid" value="user123" disabled><br/>
    <!--<button id="btn_get_token">获取 token</button> <br/>-->
    <textarea id="show_result" disabled>这里显示结果</textarea><br/>
</div>

<p> ---------------获取明星列表---------------</p>

<div>
    明星列表
    <select name="star" id="selector_star">
        <option value="null" selected>请选择</option>
    </select><br/>
</div>
</body>
<p> ---------------明星详情---------------</p>

<div>
    <button id="btn_edit">修改</button>
    <button disabled id="btn_save">保存</button>
    <br/>
    名字:<input type="text" id="input_name" class="toEdit"> <br/>
    眉毛: <input type="text" id="brow_desc" class="toEdit"/><br/>

    <img id="brow_img" src="" width="100"/>

    <div id="brow_img_new_preview"></div>
    <input type="file" class="toEdit" id="select_file_brow"/>
</div>
<p> ---------------设置眼睛顺序---------------</p>

<div>
    <button id="btn_get_all_parts">获取眼睛组件</button>
    <button id="btn_set_eye_order">保存顺序</button>
    <form id="show_eyes">

    </form>
</div>
<script src="/js/jquery.js"></script>
<script src="/js/index.js"></script>
<script>
    var show_result = $('#show_result');
    var uid = $('#input_uid').val();
    var starList;
    var token;
    var selector_star = $('#selector_star');
    function showInfo(objOrStr) {
        if (typeof objOrStr === 'object') objOrStr = JSON.stringify(objOrStr);
        show_result.val(objOrStr);
    }

    $(document).ready(function () {
        $('.toEdit').attr('disabled', 'disabled');

        // 获取token
        uid = $('#input_uid').val();
        getToken(uid, function (data, status) {
            console.log(data);
            if (data.errCode == 0)
                token = data.result.token;
            showInfo(data);
            refreshStarList();
        });
    });

    function refreshStarList() {
        getStarList(token, function (err, data) {
            if (err) return showInfo(err);
            if (data.errCode != 0) return showInfo(data);
            showInfo(data.result);

            selector_star.empty();
            selector_star.append('<option value="null" selected>请选择</option>');
            createSelectorOption(data.result, $('#selector_star'));
        });
    }


    var starid;
    var starname;
    var input_name = $('#input_name');
    var brow_desc = $('#brow_desc');
    var brow_img = $('#brow_img');
    var brow_img_new_preview = $('#brow_img_new_preview');
    var brow_data;
    var brow_desc_new;
    var brow_file_new;
    var btn_edit = $('#btn_edit');
    var btn_save = $('#btn_save');

    btn_edit.on('click', function () {
        if (!starid)return;

        btn_edit.attr('disabled', 'disabled');
        $('.toEdit').removeAttr('disabled');
        btn_save.removeAttr('disabled');
    });
    btn_save.on('click', function () {
        btn_edit.removeAttr('disabled');
        $('.toEdit').attr('disabled', 'disabled');
        btn_save.attr('disabled', 'disabled');
        saveToServer();
    });

    function createSelectorOption(cateList, selector) {
        if (!cateList || cateList.length === 0) return;
        cateList.forEach(function (item) {
            $(selector).append(
                    $('<option>', {
                        name: item.name,
                        starid: item.starid,
                        text: item.name
                    })
            );
        });
    }

    selector_star.on('change', function () {
        var selected = $("option:selected", this);
        starid = selected.attr('starid');
        starname = selected.attr('name');
        console.log('select star=%s,name=%s', starid, starname);
        brow_desc_new = null;
        brow_file_new = null;
        brow_img_new_preview.empty();
        showStarDetail();
    });

    $('#select_file_brow').on('change', function (event) {
        console.log('uploadFile');
        brow_file_new = event.target.files[0];
        if (!brow_file_new) return;
        var reader = new FileReader();
        reader.readAsDataURL(brow_file_new);
        reader.onload = function (e) {
            var fileData = e.target.result;
            brow_img_new_preview.html("<img class='itemView' width='100' padding='5px'/>");
            $('.itemView')[0].src = fileData;
        };
    });

    function atNullStar() {
        input_name.val('');
        brow_desc.val('');
        brow_img.attr('src', '');
        btn_save.trigger('click');
    }

    function showStarDetail() {
        if (!starid) return atNullStar();
        input_name.val(starname);
        getStarPart(token, starid, function (err, data) {
            if (err) return showInfo(err);
            if (data.errCode != 0) return showInfo(data);
            showInfo(data.result);
            brow_data = data.result.filter(function (item) {
                return item.otype == 0;
            })[0];
            showBrow();
        });
    }

    function showBrow() {
        var desc = (brow_data && brow_data.desc) || '';
        var url = (brow_data && brow_data.url) || '';
        brow_desc.val(desc);
        brow_img.attr('src', url);
    }

    // 这里有个bug, 如果没有眉毛数据,就会出错
    function saveToServer() {
        if (!starid) return;
        var updateStarNameDone = false;
        var updatePartsDone = false;

        function checkDone() {
            if (updateStarNameDone && updatePartsDone) refreshStarList();
        }

        // 明星的名字是否变化
        var newName = input_name.val();
        if (newName != starname) {
            updateStarName(token, starid, newName, function (err, data) {
                if (err) return showInfo(err);
                if (data.errCode != 0) return showInfo(data);
                updateStarNameDone = true;
                checkDone();
            });
        } else {
            updateStarNameDone = true;
        }


        // 处理 组件眉毛 描述图的变化
        var brow_desc_new = brow_desc.val();
        console.log('new/update 眉毛');
        var json = {
            browdesc: brow_desc_new,
            browfile: brow_file_new
        };
        updateBrow(token, starid, json, function (err, data) {
            if (err) return showInfo(err);
            if (data.errCode != 0) return showInfo(data);
            updatePartsDone = true;
            checkDone();
        });
    }
    //---------------设置眼睛顺序---------------

    $('#btn_get_all_parts').on('click', function () {
        getFaceParts(token, function (data, status) {
            console.log(data);
            if (data.errCode == 0) faceParts = data.result;
            showInfo(faceParts);
            if (!faceParts) return;

            // 眼睛
            var eye = faceParts.eye;
            showInfo(eye);
            showEyes(eye);
        });
    });
    var showEye = $('form#show_eyes');
    function showEyes(eyeArr) {
        showEye.empty();
        var ptn = '%partid: <input name="%partid" value="%order" /><br/>';
        var str;
        eyeArr.forEach(function (oneEye) {
            str = ptn
                    .replace("%partid", oneEye.partid)
                    .replace("%partid", oneEye.partid)
                    .replace("%order", oneEye.order);
            showEye.append(str)
        });
    }

    $('#btn_set_eye_order').on('click', function () {
        var obj = showEye.serialize();
        console.log(obj);
        var orders = [];
        obj.split('&').forEach(function (item) {
            var arr = item.split('=');
            orders.push({
                partid: arr[0],
                order: arr[1] || 0
            });
        });
        console.log(orders);

        updatePartsOrder(token, orders, function (err, data) {
            if (err) return showInfo(err);
            if (data.errCode != 0) return showInfo(data);
            showInfo(data.result);
        });
    });
</script>
</html>